<template>
    <div class="productBox">
        <a-spin :spinning="confirmLoading">
            <a-form-model ref="form" :model="model" :rules="validatorRules">

                <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="prodScope" label="适用商品">
                    <a-radio-group v-model="model.prodScope" @change="handelRadioProdScope('prodScope')"
                        :disabled="initProdScope != null">
                        <a-radio :style="radioStyle" :value="0">全部商品</a-radio>
                        <a-radio :style="radioStyle" :value="5">按照分类(销售价尾数)
                            <a-select v-model="model.priceTail" allowClear mode="multiple"
                                :disabled="initProdScope != null">
                                <a-select-option v-for="(item, index) in priceTail" :key="index" :value="item.value">
                                    {{ item.text }}
                                </a-select-option>
                            </a-select>
                        </a-radio>
                        <a-radio :style="radioStyle" :value="10">指定商品</a-radio>
                    </a-radio-group>
                    <div style="color: #f5222d">温馨提示：适用商品设置之后不能修改</div>
                </a-form-model-item>
                <a-form-model-item :wrapperCol="{ span: 5, offset: 5 }">
                    <a-col :md="24" :sm="24">
                        <a-form-model-item :wrapperCol="{ span: 5, offset: 5 }">
                            <a-button type="primary" htmlType="submit" @click="handelSaveProd" size="small"
                                :disabled="initProdScope != null">保存商品设置
                            </a-button>
                        </a-form-model-item>
                    </a-col>
                </a-form-model-item>
            </a-form-model>
            <SelectProductSpuListPoints ref="selectSpuForm" @ok="selectOk"></SelectProductSpuListPoints>
            <template v-if="childTab.visible">
                <a-tabs type="card" defaultActiveKey="1" style="margin-top: -15px" size="small">
                    <a-tab-pane :tab="childTab.tabNm" key="1">
                        <div class="table-operator">
                            <a-button type="primary" @click="newRow" size="small">{{ childTab.btnNm }}</a-button>
                            <a-button type="default" @click="removeAllRow" size="small">清除所有商品</a-button>
                        </div>
                        <a-table :columns="columns" :dataSource="dataSource" size="small" bordered rowKey="id"
                            :pagination="ipagination" :loading="loading" class="j-table-force-nowrap"
                            @change="handleTableChange">
                            <template slot="operation" slot-scope="text, record">
                                <a-popconfirm title="是否要删除此行？" @confirm="removeRow(record.id)"><a>删除</a></a-popconfirm>
                            </template>
                            <div slot="filterDropdown" style="padding: 8px">
                                <a-input v-ant-ref="(c) => (searchInput = c)" v-model="queryParam.itemCode"
                                    style="width: 188px; margin-bottom: 8px; display: block" />
                                <a-button size="small" style="width: 90px" @click="() => { this.loadProductList(1) }">
                                    查询
                                </a-button>
                            </div>
                            <a-icon slot="filterIcon" type="search" :style="{ color: '#108ee9' }" />
                        </a-table>
                    </a-tab-pane>
                </a-tabs>
            </template>
        </a-spin>
    </div>
</template>
  
<script>
import { postAction, getAction, deleteAction } from '@/api/manage'
import { limitNumber, filterObj } from '@/utils/util'
import SelectProductSpuListPoints from './SelectProductSpuListPoints'
import { Modal } from 'ant-design-vue'

export default {
    components: {
        SelectProductSpuListPoints,
    },
    data() {
        return {
            model: {},
            limitNumber,
            confirmLoading: false,
            validatorRules: {
                prodScope: [{ required: true, message: '必填项' }],
            },
            radioStyle: {
                display: 'block',
                height: '35px',
                lineHeight: '35px',
            },
            initProdScope: null,
            scopeType: null,
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
            childTab: {
                tabNm: '可用商品设置',
                btnNm: '',
                visible: false,
                bizType: 1,
            },
            /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
            queryParam: {},
            /* 数据源 */
            dataSource: [],
            /* 分页参数 */
            ipagination: {
                current: 1,
                pageSize: 10,
                pageSizeOptions: ['10', '20', '30'],
                showTotal: (total, range) => {
                    return range[0] + '-' + range[1] + ' 共' + total + '条'
                },
                showQuickJumper: true,
                showSizeChanger: true,
                total: 0,
            },
            /* 排序参数 */
            isorter: {
                column: 'createTime',
                order: 'desc',
            },
            /* 筛选参数 */
            filters: {},
            /* table加载状态 */
            loading: false,
            /* table选中keys*/
            selectedRowKeys: [],
            /* table选中records*/
            selectionRows: [],
            /* 查询折叠 */
            toggleSearchStatus: false,
            /* 高级查询条件生效状态 */
            superQueryFlag: false,
            /* 高级查询条件 */
            superQueryParams: '',
            /** 高级查询拼接方式 */
            superQueryMatchType: 'and',
            searchText: '',
            searchInput: null,
            searchedColumn: '',
            columns: [
            {
                    title: '品牌名称',
                    dataIndex: 'brandName',
                    width: 150,
                },
                {
                    title: '商品名称',
                    dataIndex: 'itemName',
                    width: 600,
                },
                {
                    title: '商品编码',
                    dataIndex: 'itemCode',
                    scopedSlots: {
                        filterDropdown: 'filterDropdown',
                        filterIcon: 'filterIcon',
                    },
                    onFilterDropdownVisibleChange: (visible) => {
                        if (visible) {
                            setTimeout(() => {
                                this.searchInput.focus()
                            }, 0)
                        }
                    },
                },
                {
                    title: '季节',
                    dataIndex: 'itemSession',
                },
                {
                    title: '类型',
                    dataIndex: 'itemType',
                },
                {
                    title: '零售价',
                    dataIndex: 'markPrice',
                },
                {
                    title: '操作',
                    key: 'operation',
                    scopedSlots: { customRender: 'operation' },
                },
            ],
            priceTail: [
                { text: '0', value: '0' },
                { text: '1', value: '1' },
                { text: '2', value: '2' },
                { text: '3', value: '3' },
                { text: '4', value: '4' },
                { text: '5', value: '5' },
                { text: '6', value: '6' },
                { text: '7', value: '7' },
                { text: '8', value: '8' },
                { text: '9', value: '9' },
            ],
            url: {
                saveProdScopeUrl: '/marketing/posPointsPlan/saveProdScope',
                queryById: '/marketing/posPointsPlan/queryById',
                listItemUrl: '/marketing/posPointsPlanGoods/list',
                delItemUrl: '/marketing/posPointsPlanGoods/delete',
                delAllItemUrl: '/marketing/posPointsPlanGoods/deleteAll',
            },
        }
    },
    created() {

    },
    computed: {},
    methods: {
        isPriceTail() {
            return this.model.priceTail != null && this.model.prodScope == 5 && this.model.priceTail.length > 0
        },
        show(parentModel) {
            this.model = parentModel

            //防止页面抖动
            this.model.prodScope = null
            this.model.priceTail = []

            this.scopeType = parentModel.scopeType
            this.queryProdScope()

            this.$set(this.queryParam, 'itemCode', '')
        },
        convertData() {
            console.log('---before convert---', this.model)
            if (this.scopeType == '1') {
                this.model.priceTail = this.model.priceTail
                this.model.prodScope = this.model.prodScope
            } else {
                this.model.priceTail = this.model.reducePriceTail
                this.model.prodScope = this.model.reduceProdScope
            }
            if (!this.isPriceTail()) {
                this.$set(this.model, 'priceTail', [])
            }
            console.log('---after convert---', this.model)

            let prodScope = this.model.prodScope
            this.initProdScope = prodScope

            this.switchChildTab(prodScope)
        },
        queryProdScope() {
            this.confirmLoading = true
            let that = this
            getAction(this.url.queryById, { id: this.model.id }).then((res) => {
                if (res.success) {
                    console.log('result:', res.result)
                    that.model = res.result
                    this.$nextTick(() => { that.convertData() })
                } else {
                    that.$message.warning(res.message)
                }
            }).finally(() => { this.confirmLoading = false })
        },
        handelSaveProd() {
            let param = {
                id: this.model.id,
                scopeType: this.scopeType,
            }

            let prodScope = this.model.prodScope
            let priceTail = this.model.priceTail

            if (prodScope == null) {
                this.$message.warning('适用商品必填')
                return false
            }

            if (prodScope == '5') {
                if (!priceTail) {
                    this.$message.warning('分类必填')
                    return false
                }
            }

            if (param.scopeType == '1') {
                param.prodScope = prodScope
                param.priceTail = priceTail
            } else if (param.scopeType == '2') {
                param.reduceProdScope = prodScope
                param.reducePriceTail = priceTail
            }

            let that = this
            Modal.confirm({
                title: '确定保存吗?',
                okText: '确定',
                okType: 'danger',
                cancelText: '取消',
                onOk() {
                    that.confirmLoading = true
                    postAction(that.url.saveProdScopeUrl, param).then((res) => {
                        if (res.success) {
                            that.initProdScope = prodScope
                            that.switchChildTab(prodScope)
                        }
                        that.$message.info(res.message)
                    }).finally(() => { that.confirmLoading = false })
                },
                onCancel() {
                    console.log('Cancel')
                },
            })

        },
        handelRadioProdScope(rule) {
            let selected = this.model[rule]
            if (selected == '0' || selected == '10') {
                this.$set(this.model, 'priceTail', [])
            }
        },
        switchChildTab(prodScope) {
            if (prodScope == null) {
                this.childTab.visible = false
                return
            }

            this.childTab.visible = true
            let type = 1
            //0和1 排除商品和可用商品
            if (prodScope == 0 || prodScope == 5) {
                type = 0
            }
            this.childTab.bizType = type
            if (type == 0) {
                this.childTab.tabNm = '排除商品设置'
                this.childTab.btnNm = '添加排除商品'
            } else {
                this.childTab.tabNm = '可用商品设置'
                this.childTab.btnNm = '添加可用商品'
            }

            this.loadProductList(1)
        },
        newRow() {
            this.model.bizType = this.childTab.bizType
            this.model.scopeType = this.scopeType
            this.$refs.selectSpuForm.search(this.model.orgIds, this.model)
            this.$refs.selectSpuForm.title = '选择商品'
            this.$refs.selectSpuForm.visible = true
        },
        getQueryParams() {
            //获取查询条件
            let sqp = {}
            if (this.superQueryParams) {
                sqp['superQueryParams'] = encodeURI(this.superQueryParams)
                sqp['superQueryMatchType'] = this.superQueryMatchType
            }
            var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
            param.field = this.getQueryField()
            param.pageNo = this.ipagination.current
            param.pageSize = this.ipagination.pageSize

            return filterObj(param)
        },
        getQueryField() {
            var str = 'id,'
            this.columns.forEach(function (value) {
                str += ',' + value.dataIndex
            })
            return str
        },
        handleTableChange(pagination, filters, sorter) {
            //分页、排序、筛选变化时触发
            //TODO 筛选
            console.log(pagination)
            if (Object.keys(sorter).length > 0) {
                this.isorter.column = sorter.field
                this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
            }
            this.ipagination = pagination
            this.loadData()
        },
        selectOk(selectionRows) {
            console.log('selectionRows', selectionRows)
            this.loadProductList(1)
            this.selectedRowKeys = []
            this.selectionRows = []
        },
        removeRow(id) {
            deleteAction(this.url.delItemUrl, { id: id })
                .then((res) => {
                    if (res.success) {
                        this.$message.info(res.message)
                        this.loadProductList()
                    } else {
                        this.$message.warning(res.message)
                    }
                }).finally(() => { })
        },
        removeAllRow() {
            let params = {}
            params.planId = this.model.id
            params.bizType = this.childTab.bizType
            params.scopeType = this.scopeType
            params.ruleType = 11
            let that = this
            Modal.confirm({
                title: '确定保存吗?',
                okText: '确定',
                okType: 'danger',
                cancelText: '取消',
                onOk() {
                    deleteAction(that.url.delAllItemUrl, params)
                        .then((res) => {
                            if (res.success) {
                                that.$message.info(res.message)
                                that.loadProductList()
                            } else {
                                that.$message.warning(res.message)
                            }
                        }).finally(() => { })
                },
                onCancel() {
                    console.log('Cancel')
                },
            })

        },
        loadProductList(arg) {
            //加载数据 若传入参数1则加载第一页的内容
            if (arg === 1) {
                this.ipagination.current = 1
            }
            var params = this.getQueryParams() //查询条件

            params.planId = this.model.id
            params.bizType = this.childTab.bizType
            params.prodScope = this.model.prodScope
            params.scopeType = this.scopeType
            console.log('params', params)

            this.loading = true
            getAction(this.url.listItemUrl, params)
                .then((res) => {
                    if (res.success) {
                        this.dataSource = res.result.records || res.result
                        if (res.result.total) {
                            this.ipagination.total = res.result.total
                        } else {
                            this.ipagination.total = 0
                        }
                    } else {
                        this.$message.warning(res.message)
                    }
                })
                .finally(() => {
                    this.loading = false
                })
        },
    }
}
</script>
<style scoped>
.productBox {
    border: 1px solid #e8e8e8;
    padding: 20px;
}
</style>